import { createRouter, createWebHistory } from 'vue-router'
// import { supabase } from '../config/supabase'
import DefaultLayout from '../layouts/DefaultLayout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { 
      requiresAuth: false,
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { 
      requiresAuth: false,
      title: '注册'
    }
  },
  {
    path: '/',
    component: DefaultLayout,
    meta: { title: '首页' },
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: {
          title: '首页概览',
          icon: 'HomeFilled'
        }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/users/index.vue'),
        meta: { 
          title: '用户管理',
          icon: 'User'
        },
        children: [
          {
            path: 'list',
            name: 'UserList',
            component: () => import('../views/users/UserList.vue'),
            meta: { 
              title: '用户列表',
              icon: 'List'
            }
          }
        ]
      },
      {
        path: 'students',
        name: 'Students',
        component: () => import('../views/students/index.vue'),
        meta: { 
          title: '学生管理',
          icon: 'UserFilled'
        },
        children: [
          {
            path: 'list',
            name: 'StudentList',
            component: () => import('../views/students/StudentList.vue'),
            meta: { 
              title: '学生列表',
              icon: 'Document'
            }
          },
          {
            path: 'courses',
            name: 'StudentCourses',
            component: () => import('../views/students/StudentCourses.vue'),
            meta: { 
              title: '课程分配',
              icon: 'ChatDotRound'
            }
          },
          {
            path: 'expiring',
            name: 'ExpiringStudents',
            component: () => import('../views/students/ExpiringStudents.vue'),
            meta: { 
              title: '到期学生',
              icon: 'Calendar'
            }
          }
        ]
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 修改路由守卫逻辑
router.beforeEach(async (to, from, next) => {
  // 从localStorage获取accessToken
  const accessToken = localStorage.getItem('accessToken')
  const userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : null
  
  if (to.meta.requiresAuth !== false && !accessToken) {
    next('/login')
  } else if ((to.path === '/login' || to.path === '/register') && accessToken) {
    next('/')
  } else {
    next()
  }
})

export default router
